package com.server.rpcserver;


import com.common.code.MyNettyDecoder;
import com.common.code.MyNettyEncoder;
import com.common.serialize.CommonSerializer;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * @author Zixiang Hu
 * @description
 * @create 2021-02-28-16:15
 */
@Slf4j
@Builder
@AllArgsConstructor
public class NettyServerInitializer extends ChannelInitializer<SocketChannel> {
    private ServiceProvider serviceProvider;
    private CommonSerializer serializer;

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        // 添加心跳检测机制，如果长时间没有读信号则断开连接
        pipeline.addLast(new IdleStateHandler(10, 0, 0, TimeUnit.SECONDS));
        // 添加解码器
        pipeline.addLast(new MyNettyDecoder());
        // 添加编码器
        pipeline.addLast(new MyNettyEncoder(serializer));
        // 添加服务端的处理逻辑
        pipeline.addLast(new NettyServerHandler(serviceProvider));
    }
}
